<?php
include_once("../configure/configure.php");		//--> global var
include_once("../admin/lib/utils/StringUtils.php");

include_once("Common.php");
include_once("Files.php");

$oCommon 	= new Common();
$oFiles		= new Files();		//--> Files

set_time_limit(0);

/* 0: Id, 1: Name, 2: Advertiser Id, 3: Advertiser name, 4: Tracking URL, 5: Creative URL, 6: Image Size, 7: Tracking html code,
 * 8: Start Date, 9: End Date, 10: Creative Type, 11: Category, 12: Promotion Type, 13: Advertiser 3 month EPC, 14: Advertiser 7 day EPC, 
 * 15: Merchandising Text
 * 
 */
$merNewFeedPath = "../feed/cj/product/new/";
$merOldFeedPath = "../feed/cj/product/old/";

$arrFileList = $oFiles->listFileName($merNewFeedPath);
foreach($arrFileList as $name){
	$row = 0;
	
	$handle = fopen($merNewFeedPath . $name, "r");
	while ($data = fgetcsv($handle)) {
		if($row == 0){// skip title
			$row++;
			continue;
		}
		
		
		$name 				= $data[1];
		$advertiserId 		= $data[2];
		$trackingURL		= $data[4];
		$creativeURL		= $data[5];
		$imageSize 			= $data[6];
		$trackingHtmlCode	= $data[7];
		$startDate			= $data[8];
		$endDate			= $data[9];
		
		$creativeType		= $data[10];
		$categoryName 		= $data[11];
		
		$promotionType 		= $data[12];
		$merchandisingText	= $data[15];
		
		$brandId 			= 0;
		$categoryId			= 0;
		
		$imageWidth			= 0;
		$imageHeight		= 0;
		
		$code			= '';
		
		// filter
		if(!empty($imageSize)){
			$imageWH = explode('x', $imageSize);
			
			$imageWidth 	= $imageWH[0];
			$imageHeight	= $imageWH[1];
		}
		
		
		$merchantID = $oCommon->getColumn(DB_TAG_COUPON, "SELECT ma.merchantId FROM merchant_attributes ma" .
				" WHERE ma.attributeId = 5 AND ma.attributeValue = '$advertiserId'");
				
		if(!empty($merchantID)){
			
			$categoryId = $oCommon->getColumn(DB_TAG_COUPON, "SELECT id FROM category WHERE name LIKE '%$categoryName%'");
			
			if(empty($categoryId)){
				$sql_data_array = array(
					'name' 		=> $categoryName,
					'descript' 	=> '',
					'title' 	=> '',
					'status' 	=> '1',
					'parentId' 	=> '-1'
				);
					
				$categoryID = $oCommon->insertUpdate(DB_TAG_COUPON, 'category', $sql_data_array);
			
			
//				echo 'sql = ' . "SELECT id FROM category WHERE name = '$categoryName'" . '<br>';
//				continue;
			}
			
			if(!empty($categoryId)){
				$mcID = $oCommon->getColumn(DB_TAG_COUPON, "SELECT categoryId FROM merchant_category WHERE merchantId = $merchantID AND categoryId = $categoryId");
				if(empty($mcID)){
					$sql_data_array = array(
						'merchantId' 		=> $merchantID,
						'categoryId' 		=> $categoryId
					);
						
					$oCommon->insertUpdate(DB_TAG_COUPON, 'merchant_category', $sql_data_array, 'insert', " ON DUPLICATE KEY UPDATE merchantId=Values(merchantId)");
				
					echo "merchantId_categoryId = $merchantID_$categoryID<br>";
					
				}
			}
			
			if($creativeType == 'Banner'){
				if(empty($imageWidth))
					$imageWidth = 1;

				if(empty($imageHeight))
					$imageHeight = 1;
				
				$creativeType = '1';
			}else if ($creativeType == 'Text'){
				$creativeType = '2';
			}else if ($creativeType == 'Search Box'){
				$creativeType = '3';
			}else
				$creativeType = '2';
				
			if ($promotionType == 'Coupon'){
				$startFlag 	= 'with coupon code ';
				$endFlag	= '. expirat';
				
				$code 	= StringUtils::getCutValue($startFlag, $endFlag, $name);
				$name 	= StringUtils::getStartValue(' with coupon code', $name);
			}
			
			$attributeIdForPromoType = getAttributeIdForPromoType($promotionType);
			
			if(empty($startDate)){
				$startDate = 'null';
			}else{
				$startDate = date('Y-m-d', strtotime($startDate));
			}
			
			if(empty($endDate)){
				$endDate = 'null';
			}else{
				$endDate = date('Y-m-d', strtotime($endDate));
			}
			
			if(empty($creativeURL)){
				$creativeURL = 'null';
			}
			
			
			$pattern[0] = "/(\d+)x(\d+)/i";
			$pattern[1] = "/(\d+) x (\d+)/i";

			$replacement 	= '';
			$filtername 	= preg_replace($pattern[0], $replacement, $name);
			$filtername 	= preg_replace($pattern[1], $replacement, $filtername);
			$filtername 	= str_ireplace ('banner', $replacement, $filtername);
			$filtername 	= str_ireplace (' logo', $replacement, $filtername);
			$filtername 	= str_ireplace (' Logo', $replacement, $filtername);
			
			$filtername 	= trim($filtername, ' ');
			$filtername 	= trim($filtername, '-');
			$filtername 	= trim($filtername, '_');
			$filtername 	= trim($filtername, ' ');
			
			$IDkey			= md5($merchantID . $code . $filtername . $descript);
			
			
			$couponID = $oCommon->getColumn(DB_TAG_COUPON, "SELECT id FROM coupon WHERE IDKey = '$IDkey'");
			
			if(empty($couponID) && !empty($filtername)){
				$sql_data_array = array(
					'name' 				=> $filtername,
					'merchantId'		=> $merchantID,
					'descript' 			=> $merchandisingText,
					'trackingURL' 		=> $trackingURL,
					'trackingHtmlCode' 	=> $trackingHtmlCode,
					
					'startDate' 		=> $startDate,
					'endDate' 			=> $endDate,
					
					'creativeType' 		=> $creativeType,
					
					'code' 				=> $code,
					'sourceId'			=> '1',
					'status' 			=> "1",
					'createdTime' 		=> "UTC_TIMESTAMP()",
					'IDkey' 			=> $IDkey
				);
				
				$couponID = $oCommon->insertUpdate(DB_TAG_COUPON, 'coupon', $sql_data_array, 'insert', " ON DUPLICATE KEY UPDATE modifiedTime=Values(modifiedTime)");
				echo "insert coupon id = $couponID <br>";
				
				if(!empty($couponID)){
					$sql_data_array = array(
						'couponId'			=> $couponID,
						'categoryId' 		=> $categoryId,
					);
					
					$oCommon->insertUpdate(DB_TAG_COUPON, 'coupon_category', $sql_data_array, 'insert', " ON DUPLICATE KEY UPDATE categoryId=Values(categoryId)");
					
					
					if(!empty($attributeIdForPromoType)){
						$sql_data_array = array(
							'couponId'			=> $couponID,
							'attributeId' 		=> $attributeIdForPromoType,
							'attributeValue' 	=> 'Promo Type'
						);
						
						$oCommon->insertUpdate(DB_TAG_COUPON, 'coupon_attributes', $sql_data_array, 'insert', " ON DUPLICATE KEY UPDATE attributeValue=Values(attributeValue)");
					}
				}
				
				if(!empty($couponID) && $creativeType == 1){
					$sql_data_array = array(
						'name' 				=> $name,
						'couponId'			=> $couponID,
						
						'creativeURL' 		=> $creativeURL,
						'width' 			=> $imageWidth,
						'height' 			=> $imageHeight,
						
						'useType' 			=> '0',
						'status' 			=> "1"
						
					);
						
					$couponImageId = $oCommon->insertUpdate(DB_TAG_COUPON, 'coupon_images', $sql_data_array, 'insert', " ON DUPLICATE KEY UPDATE modifiedTime=Values(modifiedTime), creativeURL=Values(creativeURL)");
					echo "coupon image id = $couponImageId <br>";
				}
			}else{
//				echo "coupon is existed.<br>";
			}
		}else{
			echo "$advertiserId advertiserId is not existed.<br>";
		}
	}
	
	fclose($handle);


}

$oFiles->moveFiles($merNewFeedPath, $merOldFeedPath);

function getAttributeIdForPromoType($promoTypeName)
{
	$attribteId = 0;
	
	switch ($promoTypeName) {
	    case "Ongoing Promotion":
	        $attribteId = 31; 
	        break;
	    case "Sale":
	       $attribteId = 32; 
	        break;
	    case "Coupon":
	        $attribteId = 33; 
	        break;
	    case "Unspecified":
	        $attribteId = 34; 
	        break;
	    case "Price Cut":
	        $attribteId = 35; 
	        break;
	    case "Product Promotion":
	        $attribteId = 36; 
	        break;
	    case "Free Shipping":
	        $attribteId = 2; 
	        break;
	    case "Percent Off":
	        $attribteId = 1; 
	        break;
	    case "Free Gift":
	        $attribteId = 37; 
	        break;
	    case "Sweepstakes":
	        $attribteId = 38; 
	        break;
	    case "Free Gift Wrap":
	        $attribteId = 39; 
	        break;
	    case "Buy x Get y":
	        $attribteId = 40; 
	        break;

	}
}



?>